package com.eportal.action;

import com.eportal.domain.Sysopt;
import com.framework.excelTools.DoExcel;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.JsonUtil;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageInfo;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;


/**
 * Created by smzhang on 2015/12/17.
 */
public class BaseAction extends ActionSupport {

	private static Logger log = Logger.getLogger(BaseAction.class.getName());

    public HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    public HttpSession getSession() {
        return getRequest().getSession();
    }

    public HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

   /* *
    *
    *以Json格式返回参数
    @param
    params
    *@throws IOException*/

    public static void responseBody(Map<String, Object> params){
        try {
        	HttpServletResponse response = ServletActionContext.getResponse();
        	response.setCharacterEncoding("UTF-8");
        	response.setContentType("text/html");
        	JSONObject json = JSONObject.fromObject(params);
        	response.getWriter().print(json);
		} catch (Exception e) {
			log.error("输出json值到页面失败",e);
		}
    }


    public static void responseBody(List params) throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        JSONArray json = JSONArray.fromObject(params);
        out.write(json.toString());
    }

    public static void responseBody(String params) throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.write(params);
    }


    /*struts2文件上传*/
    private File upload;
    private String uploadFileName;
    private String uploadContentType;

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    /* *
      * 设置分页
      *
      * @param request
      * @param jqGridPager
    */
    public void setPage(HttpServletRequest request, JqGridPager jqGridPager) {
        jqGridPager.setId(request.getParameter("id"));
        jqGridPager.setPager(Integer.valueOf(request.getParameter("page") == null ? "0" : request.getParameter("page")));
        jqGridPager.setTotal(Integer.valueOf(request.getParameter("total") == null ? "0" : request.getParameter("total")));
        jqGridPager.setRows(Integer.valueOf(request.getParameter("rows") == null ? "0" : request.getParameter("rows")));
        jqGridPager.setPgButton(request.getParameter("pgButton"));
        jqGridPager.setSord(request.getParameter("sord"));
        jqGridPager.setSidx(request.getParameter("sidx"));
        jqGridPager.setExporttype(request.getParameter("exporttype"));
        jqGridPager.setIsexport(request.getParameter("export"));
    }


    public String jqGridQueryMap(Class elementType, HttpServletRequest request, List<?> listdata,
                                 HttpServletResponse response, JqGridPager jqGridPager) throws Exception {

        try {
            if (request.getParameter("export") != null && "excel".equals(request.getParameter("export"))) {
                javax.servlet.ServletOutputStream servletoutputstream = response
                        .getOutputStream();
                response.reset();//必须加，不然保存不了临时文件
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=data.xls");
                if (jqGridPager.getExportCol() != null) {
                    DoExcel.cols = getText(jqGridPager.getExportCol());
                    DoExcel.colsname = getText(jqGridPager.getExportCol() + "_name");
                }
                DoExcel.excelMapExport(request, listdata, servletoutputstream);
                return null;
            } else {
                response.setContentType("text/xml; charset=UTF-8");//传输xml时要用html
                response.setCharacterEncoding("UTF-8");
                PrintWriter pw = response.getWriter();
                pw.write(JsonUtil.spanJson(elementType, listdata, jqGridPager, request));
            }


        } catch (Exception ex) {
        	log.error(this, ex);
        }
        return null;

    }

    /**
     * 获取用户id
     * @Author Saber
     * @Date 2017/7/10 下午6:59
     * @return 用户id
     */
    public Long getOptId(){
        Sysopt user = (Sysopt) getSession().getAttribute("user");
        return user.getSid();
    }

    /**
     * 构建返回给jqgrid的分页json数据
     * @param pageInfo
     * @param pageEntity
     * @return
     */
    public static String buildResponseJSON(PageInfo<?> pageInfo,PageEntity pageEntity){
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();

        json.put("total",pageInfo.getPages());//总页数
        json.put("page",pageEntity.getPageNo());//当前页
        json.put("records",pageInfo.getTotal());//总记录数
        json.put("rows", pageInfo.getList());//list

        return json.toJSONString(json);
    }

    public void writeResponseJSON(PageInfo<?> pageInfo,PageEntity pageEntity,HttpServletResponse response){
        response.setContentType("text/plain; charset=UTF-8");//传输xml时要用html
//                response.setContentType("text/xml; charset=UTF-8");//传输xml时要用html
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(buildResponseJSON(pageInfo,pageEntity));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }

    }
}
